package shiyl.use.springboot.requestparam.common;

import com.google.gson.GsonBuilder;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.format.Formatter;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import static java.lang.String.format;

/**
 * <pre>
 * 字符串和日期之间的转换
 * 时间戳 <--> 字符串
 * 时间   <--> 字符串
 * 日期   <--> 字符串
 * </pre>
 */
@Component
public class String2DateFormatter implements Formatter<Date>{

    private static final String DATE_SHOW_FORMAT = "yyyy-MM-dd HH:mm:ss:SSS";
    private static final String DATE_TIMESTAMP_FORMAT = "yyyyMMddHHmmssSSS";
    private static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
    private static final String DATE_FORMAT = "yyyy-MM-dd";

    /**
     * Parse a text String to produce a T.
     *
     * @param text   the text string
     * @param locale the current user locale
     * @return an instance of T
     * @throws ParseException           when a parse exception occurs in a java.text parsing library
     * @throws IllegalArgumentException when a parse exception occurs
     */
    @Override
    public Date parse(String text, Locale locale) throws ParseException {
        // 用长度来判断转换类型
        int len = text.length() ;
        if( 10 == len ){
            // 10位 日期
            return new SimpleDateFormat(DATE_FORMAT).parse(text);
        }
        if( 20 == len ){
            // 20位 时间
            return new SimpleDateFormat(DATE_TIME_FORMAT).parse(text);
        }
        if( 17 == len ){
            // 17位 时间戳
            return new SimpleDateFormat(DATE_TIME_FORMAT).parse(text);
        }
        throw new ParseException(format("无法识别为日期类型的字符串[%s]",text),0) ;
    }

    /**
     * Print the object of type T for display.
     *
     * @param object the instance to print
     * @param locale the current user locale
     * @return the printed text string
     */
    @Override
    public String print(Date object, Locale locale) {
        return new GsonBuilder().setDateFormat(DATE_SHOW_FORMAT).create().toJson(object);
    }
}
